using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Text.RegularExpressions;

namespace AlbumGet
{
    public partial class Form1 : Form
    {
        public SmugMug smugmug = null;
        private long prevBytes = 0;
        private DateTime prevTime = DateTime.Now;

        private Downloader downloader = new Downloader();
        public Form1()
        {
            InitializeComponent();

            smugmug = new SmugMug(txtAPIKey.Text);

            smugmug.Log += new SmugMug.LogEvent(smugmug_Log);

            //downloader.SkipIfFileExists = false;
            downloader.SingleFileStarted += new Downloader.SingleFileEvent(downloader_SingleFileStarted);
            downloader.SingleFileFinished += new Downloader.SingleFileEvent(downloader_SingleFileFinished);
            downloader.AllFilesFinished += new Downloader.MultipleFileEvent(downloader_AllFilesFinished);
            downloader.SingleFileProcessChanged += new Downloader.SingleFileProgressChange(downloader_SingleFileProcessChanged);
            downloader.LogEvent += new Downloader.GenericLog(downloader_LogEvent);
        }

        void downloader_SingleFileStarted(string URL, int FileNumber, int TotalFiles)
        {
            smugmug_Log(string.Format("File {0}/{1}: {2} download started", FileNumber, TotalFiles, URL));
        }

        void downloader_SingleFileProcessChanged(string URL, int PercentFinished)
        {
            progressSingleFile.Value = PercentFinished;
        }

        void downloader_LogEvent(string Message)
        {
            smugmug_Log(Message);
        }

        void downloader_AllFilesFinished(int FileCount)
        {
            MessageBox.Show("All files finished downloading.");
            smugmug_Log("All files finished.");

            // RESET PROGRESS TO ZERO
            progressTotal.Value = 0;
        }

        void downloader_SingleFileFinished(string URL, int FileNumber, int TotalFiles)
        {
            progressTotal.Value = (int)((FileNumber / (float)TotalFiles) * 100);
            progressSingleFile.Value = 0;
            smugmug_Log(string.Format("File {0}/{1}: {2} was downloaded", FileNumber, TotalFiles, URL));
        }

        void smugmug_Log(string Message)
        {
            toolStripStatus1.Text = Message;
            statusStrip1.Refresh();

            lstLog.Items.Add(Message);
            lstLog.Refresh();
        }

        private SmugMug.AlbumImage GetImageInformation(ListViewItem item)
        {
            int thisImageID = 0;
            SmugMug.AlbumImage res = null;
            if (int.TryParse(item.Text, out thisImageID) && item.Tag == null)
            {
                SmugMug.AlbumImage img = smugmug.GetImageInfo(thisImageID);
                item.SubItems.Add(img.SizeString);
                item.SubItems.Add(img.OrignalURL);
                item.Tag = img;

                res = img;
            }
            else if (item.Tag != null && item.Tag is SmugMug.AlbumImage)
                res = (SmugMug.AlbumImage)item.Tag;

            return res;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void btnGetImageList_Click(object sender, EventArgs e)
        {
            // fill image list with image IDs
            int AlbumID = 0;
            if (int.TryParse(txtAlbumID.Text, out AlbumID))
            {
                GetImageList(AlbumID);
            }
            else
                MessageBox.Show("No AlbumID specified.");
        }

        private void GetImageList(int AlbumID)
        {
            if (AlbumID > 0)
            {
                List<int> imageIDs = smugmug.GetAlbumImages(AlbumID);

                lstImages.Items.Clear();

                for (int a = 0; a < imageIDs.Count; a++)
                {
                    ListViewItem item = new ListViewItem(imageIDs[a].ToString());

                    lstImages.Items.Add(item);

                    //GetImageInformation(item);
                }
            }
            else
                MessageBox.Show("No AlbumID specified.");
        }

        private void btnDownloadLocation_Click(object sender, EventArgs e)
        {
            if (folderDownloadLocation.ShowDialog() == DialogResult.OK)
            {
                AlbumGet.Properties.Settings.Default.download_location = folderDownloadLocation.SelectedPath;
                AlbumGet.Properties.Settings.Default.Save();

                txtDownloadLocation.Text = folderDownloadLocation.SelectedPath;
            }
        }

        private void btnCancelBatch_Click(object sender, EventArgs e)
        {
            downloader.CancelBatchDownloads();
        }

        private void btnDownloadAllImages_Click(object sender, EventArgs e)
        {
            // CHECK FOR ALBUM ID
            if (txtAlbumID.Text.Length == 0)
            {
                MessageBox.Show("No album selected. Please select an album.", "No album selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (txtDownloadLocation.Text.Length == 0)
            {
                if (MessageBox.Show("No download folder specified. Would you like to specify a folder to download to?", "Specify download folder?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    btnDownloadLocation_Click(null, null);
                }
            }

            if (!System.IO.Directory.Exists(txtDownloadLocation.Text))
            {
                MessageBox.Show("Download directory does not exist.");
            }
            else if (MessageBox.Show("Download all images to " + txtDownloadLocation.Text + "?", "Download Images?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                SmugMug.AlbumImage image = null;
                List<string> URLs = new List<string>();
                for (int a = 0; a < lstImages.Items.Count; a++)
                {
                    image = null;
                    if (lstImages.Items[a].Tag == null)
                        GetImageInformation(lstImages.Items[a]);

                    if (lstImages.Items[a].Tag is SmugMug.AlbumImage)
                    {
                        image = (SmugMug.AlbumImage)lstImages.Items[a].Tag;

                        URLs.Add(image.OrignalURL);
                    }
                }

                downloader.URLs = URLs.ToArray();
                downloader.DestinationFolder = txtDownloadLocation.Text;
                downloader.StartBatchDownload();
            }
        }

        private void lstImages_DoubleClick(object sender, EventArgs e)
        {
            for (int a = 0; a < lstImages.SelectedItems.Count; a++)
            {
                SmugMug.AlbumImage img = GetImageInformation(lstImages.SelectedItems[a]);
                lblImageDetails.Text = "Image Details: \n" + img.ToString();
            }
        }

        private void btnGetUserAlbums_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;
            if (username.Length == 0)
            {
                MessageBox.Show("No username specified. Please enter one to get a list of albums.", "No username", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (txtAPIKey.Text.Length == 0)
            {
                MessageBox.Show("No API key specified. \n\nPlease enter your API key from SmugMug to get a list of albums.", "No username", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                AlbumGet.Properties.Settings.Default.Save();

                List<SmugMug.AlbumInfo> albums = smugmug.GetUserAlbums(username);

                foreach (SmugMug.AlbumInfo album in albums)
                {
                    AddAlbum(username, album);
                }
            }
        }

        private void AddAlbum(string Username, SmugMug.AlbumInfo Album)
        {
            TreeNode thisUser = null;

            for (int a = 0; a < treeUserAlbums.Nodes.Count && thisUser == null; a++)
            {
                if (treeUserAlbums.Nodes[a].Text == Username)
                    thisUser = treeUserAlbums.Nodes[a];
            }

            if (thisUser == null)
            {
                thisUser = new TreeNode(Username);
                treeUserAlbums.Nodes.Add(thisUser);
            }

            // FIND CATEGORY
            TreeNode thisCategory = null;
            for (int a = 0; a < thisUser.Nodes.Count && thisCategory == null; a++)
            {
                if (thisUser.Nodes[a].Text == Album.Category)
                    thisCategory = thisUser.Nodes[a];
            }

            if (thisCategory == null)
            {
                thisCategory = new TreeNode(Album.Category);
                thisUser.Nodes.Add(thisCategory);
            }

            // FIND ALBUM IN CATEGORY
            SmugMug.AlbumInfo thisAlbum = null;
            for (int a = 0; a < thisCategory.Nodes.Count && thisAlbum == null; a++)
            {
                if (thisCategory.Nodes[a].Tag is SmugMug.AlbumInfo &&
                    ((SmugMug.AlbumInfo)thisCategory.Nodes[a].Tag).AlbumID == Album.AlbumID)
                    thisAlbum = Album;
            }

            // Add if doesn't exist
            if (thisAlbum == null)
            {
                TreeNode newAlbum = new TreeNode(Album.Title);
                newAlbum.Tag = Album;
                newAlbum.ToolTipText = "Double-click to get list of images.";

                thisCategory.Nodes.Add(newAlbum);
            }
        }

        private void treeUserAlbums_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node != null &&
                e.Node.Tag != null &&
                e.Node.Tag is SmugMug.AlbumInfo)
            {
                lstImages.Items.Clear();

                SmugMug.AlbumInfo album = (SmugMug.AlbumInfo)e.Node.Tag;

                txtAlbumID.Text = album.AlbumID.ToString();

                GetImageList(album.AlbumID);
            }
        }

        private void txtAPIKey_TextChanged(object sender, EventArgs e)
        {
            // SET API KEY in SMUGMUG INSTANCE
            smugmug.API_Key = txtAPIKey.Text;

            // SAVE IN SETTINGS
            AlbumGet.Properties.Settings.Default.api_key = txtAPIKey.Text;
            AlbumGet.Properties.Settings.Default.Save();
        }
    }
}